package com.yz.test.parking.sign;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;


/**
 * 名称：支付类调取异步返回处理帮助类
 * 功能：辅助异步返回进行验证、写日志等动作
 * 接口名称：标准即时到账接口
 * 版本：2.0
 * 日期：2008-12-25
 * 作者：支付宝公司销售部技术支持团队
 * 联系：0571-26888888
 * 版权：支付宝公司
 * */
public class SignatureHelper {
	private static Logger logger = LoggerFactory.getLogger(SignatureHelper.class);

	public static final String CharSet = "utf-8";

	public static String sign(Map<String,String> params, String privateKey) {
		return sign(params,privateKey,"RSA");
	}

	public static String sign(Map<String,String> params, String privateKey,String signType) {
		String content = getSignVerifyContent(params);
		if ("RSA".equals(signType)){
			return sign(content, privateKey,signType);
		}else if ("RSA2".equals(signType)){
			return sign(content, privateKey,signType);
		}
		return sign(content, privateKey,"RSA");
	}

	public static String getSignVerifyContent(Map params) {
		Properties properties = new Properties();
		for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			Object value = params.get(name);

            if (name == null || name.equalsIgnoreCase("sign") || name.equalsIgnoreCase("sign_type")
                    || name.equalsIgnoreCase("ip")) {
				continue;
			}
			properties.setProperty(name, value.toString());
		}
		String content = getSignatureContent(properties);
		return content;
	}
	public static String getSignatureContent(Properties properties) {
		StringBuffer content = new StringBuffer();
		List keys = new ArrayList(properties.keySet());
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			String value = properties.getProperty(key);
			if(StringUtils.isBlank(key)|| StringUtils.isBlank(value)){
				continue;
			}
			content.append((content.length() == 0 ? "" : "&") + key + "=" + value+"");
		}
		return content.toString();
	}
	public static String sign(String content, String privateKey) {
		return sign(content, privateKey,"RSA");
	}

	public static String sign(String content, String privateKey,String signType) {
		if (privateKey == null) {
			return null;
		}
		if ("RSA".equalsIgnoreCase(signType)){
			return RSA.sign(content, privateKey, CharSet);
		} else if ("RSA2".equalsIgnoreCase(signType)){
			return RSA2.sign(content, privateKey, CharSet);
		}
		return RSA.sign(content, privateKey, CharSet);
	}

	public static boolean verify(Map<String,String> params, String sign, String publicKey, String signType) {
		String content = getSignVerifyContent(params);
		if ("RSA".equals(signType)){
			return verify(content,sign,publicKey,signType);
		}else if ("RSA2".equalsIgnoreCase(signType)){
			return verify(content,sign,publicKey,signType);
		}
		return verify(content,sign,publicKey,"RSA");
	}

	public static boolean verify(Map<String,String> params, String sign,String publicKey) {
		String content = getSignVerifyContent(params);
		return verify(content,sign,publicKey,"RSA");
	}

	public static boolean verify(String content, String sign,String publicKey,String signType){
		logger.debug("SignatureHelper sign verify,content={},sign={},publicKey={}",content,sign,publicKey);
		if ("RSA".equalsIgnoreCase(signType)){
			return RSA.verify(content, sign, publicKey, CharSet);
		}else if ("RSA2".equalsIgnoreCase(signType)){
			return RSA2.verify(content, sign, publicKey, CharSet);
		}
		return RSA.verify(content, sign, publicKey, CharSet);
	}


	/**
	 * 2014年11月16日 lidongliang
	 * 调用此方法前，请将parms的sign和sign_type先去掉
	 * @param params
	 * @param privateKey
	 * @return
	 */
	public static String unOrderSign(Map<String,String> params, String privateKey) {
		StringBuilder content = new StringBuilder();
		boolean isFirst = true;
		for(Map.Entry<String, String> entry : params.entrySet()){
			String key = entry.getKey();
			String value = entry.getValue();
			content.append((isFirst == true ? "" : "&") + key + "=" + value+"");
			if(isFirst){
				isFirst = false;
			}
		}
		return RSA.sign(content.toString(), privateKey, CharSet);
	}

	public static void main (String[] args) {
//		Map<String,String> params = new HashMap<String, String>();
//		params.put("buyer_id", "2088002184091500");
//		params.put("trade_no", "2015080700001000500059874101");
//		params.put("body", "物流单1");
//		params.put("use_coupon", "N");
//		params.put("notify_time", "2015-08-07 16:44:15");
//		params.put("subject", "物流单1");
//		params.put("sign_type", "RSA");
//		params.put("is_total_fee_adjust", "N");
//		params.put("notify_type", "trade_status_sync");
//		params.put("out_trade_no", "T4231840000");
//		params.put("trade_status", "TRADE_SUCCESS");
//		params.put("gmt_payment", "2015-08-07 16:20:03");
//		params.put("discount", "0.00");
//		params.put("gmt_create", "2015-08-07 16:20:03");
//		params.put("buyer_email", "novelty-fish@163.com");
//		params.put("price", "0.01");
//		params.put("total", "0.01");
//		params.put("quantity", "1");
//		params.put("seller_id", "2088411506548729");
//		params.put("seller_email", "55market@55tuan.com");
//		params.put("notify_id", "b037c5090c3babbeb058b5558827ffff4s");
//		params.put("payment_type", "8");
//		String sign = "Gx47be9W6LurOwG3wSDsDQ8YuNXWCj2x95yFORXL6KqQeFiq8bM62mLf+eSzWB8VI0bT4MFmwyPL4qsTJTSZ4W0apIFjPCFe6EaZ3/mdGwwDEjyVP6k0WIWayfU6fEQ6jb1oYSCwaAxABVa/P2+vB8w12mZFx+rDEFrqyWMZquM=";
//		params.put("sign", sign);
//		String publicKe1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
//		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuE0sEjDyk+jPSUFtNWfxty4ZQNa6GsHlJj0qse6CRkG/B90lOG5XaoQ3ts6kV8vJL/zPBjfcjNotbd4liAHqBAzDu6X6QeRc3EzdS8Fx/ljW/FXufSnfL/PtpPW47S2CIXLrhcagVYd33p0Xbk7lJZDpJLsoQy0N2RsAbsCqDPQIDAQAB";
//		String publickee = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
//		boolean bool = verify(params,sign,publicKey);
//		System.out.println(bool);

		String sign = "gpk84LUAZdeXx0yDbVPRjavtJu8rECyXkyELIic8XMEPv6xRMjALMhgU0v2GFN7fZ7MZL+CUGOoOAhsHXUjtxll3fLkB0mjNW3AJliyPArtDWIV7vNYtEIZEW7pRRawTqAhEJ5dErSwxPSv/ATaySZQ8uCcOGoZ25Qw0Cy66U1A=";
		String s = "gpk84LUAZdeXx0yDbVPRjavtJu8rECyXkyELIic8XMEPv6xRMjALMhgU0v2GFN7fZ7MZL+CUGOoOAhsHXUjtxll3fLkB0mjNW3AJliyPArtDWIV7vNYtEIZEW7pRRawTqAhEJ5dErSwxPSv/ATaySZQ8uCcOGoZ25Qw0Cy66U1A=";
		System.out.println(sign.equals(s));
		String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMqnmT2/IbaX337ToGt+0y/hR816UEb9F3HUwCqSqesE5otgRmGS5ztQ+SSZSkDTEa/zd5+vPqvtSPwGoiiZ5t2yTPiLqW7JtxDsRJzUZZilkEHINETBgGLw/SOS6z/11RWkQFNfUMCiqoC8a7OVUqEiEMOtjRyPq6onml8j8BCnAgMBAAECgYEApx870p3ykYABgbfITZ3TT2L7McqytTg2w1rt9q3ojrYF4d7Na94X7uTB8Zqwj3EA3xdrCTcd+e6/B4f45n600ZrEggL85PgJ+padCifZMGRQVKyTWLXVujZEANj6h00DlBPA1aflX4lCuvr7jwTd+x/pPlkIOZEvccH3YdwrlKECQQDx3qy5EDDxUCTGzxnzt4E9/SfcwdXVaxME2/O9w4ZbJ04i7nH9JF5qqajMaohbSY7kQ1Dkbk9B1G1sUIgQGQEPAkEA1n5vaDx/QTr2fQ1M0XMs1fcAz5XqIyQBVyjCoy+WLQKsw880+55q9bAqstd3hgbCgRS5oGHGscVgGT/zYtxG6QJAf16T9qDgJTPfKhLFx+JK3SoDY+1vfgP08AokQTpF9pqsOxj2Tiho0CKoEX3IcMo7xVjtsF2mvzPuq6t8+30vYQJAczwADGccEuZjkHF5yLjw6I7ID75ByNlKIxJR5yvkqY/bU2NZ2qiUXCRl/CkIHKg7DPAefgypm84nP8l8r6saKQJAbcOdQzJ4DFfRAkPQ+pdPxDfxFLWrDVPdSG5yR1gmb1swNdQq88lvoSIS/qUpSUPZ0eb1g3n/xvW/fNWq7Fuajg==";
		Map<String,String> params1 = new HashMap<String, String>();
		params1.put("sign", sign);
		params1.put("timestamp", "1458876209206");
		params1.put("api_name", "yunzong.campaign.activity.create");
		params1.put("biz_context", "{\"out_biz_no\":\"order1391391392089913\",\"camp\":{\"camp_type\":\"DRAW_PRIZE\",\"camp_name\":\"\\u9886\\u5238\\u6d3b\\u52a8\",\"camp_alias\":\"\\u9886\\u5238\",\"camp_start_time\":\"2016-03-19 00:00:00\",\"camp_end_time\":\"2016-08-19 00:00:00\",\"camp_desc\":\"\\u9886\\u5238\\u6d3b\\u52a8\\u8be6\\u7ec6\\u8bf4\\u660e\"},\"prize\":{\"prize_type\":\"VOUCHER_TICKET\",\"prize_name\":\"88\\u6298\\u4ee3\\u91d1\\u5238\",\"prize_desc\":\"88\\u6298\\u4ee3\\u91d1\\u5238\\u8be6\\u7ec6\\u8bf4\\u660e\",\"prize_template_start_time\":\"2016-03-19 00:00:00\",\"prize_template_end_time\":\"2016-08-19 00:00:00\",\"prize_use_count\":\"1\",\"prize_worth_amount\":\"10\",\"prize_base_rule_amount\":\"100\",\"prize_suitable_shops\":[\"1\",\"2\",\"3\"],\"prize_relative_time\":{\"dimension\":\"D\",\"value\":\"7\"}},\"budget\":{\"budget_type\":\"CAMP_BUDGET_AMOUNT\",\"budget_total\":\"10000\"}}");
		params1.put("sign_type", "RSA");
		params1.put("charset", "UTF-8");
		params1.put("service_name", "wanglongmarketing");
		params1.put("version", "1.0");
		final String sign1 = sign(params1, privateKey);
		System.out.println(sign1);
		String pk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKp5k9vyG2l99+06BrftMv4UfNelBG/Rdx1MAqkqnrBOaLYEZhkuc7UPkkmUpA0xGv83efrz6r7Uj8BqIomebdskz4i6luybcQ7ESc1GWYpZBByDREwYBi8P0jkus/9dUVpEBTX1DAoqqAvGuzlVKhIhDDrY0cj6uqJ5pfI/AQpwIDAQAB";
		boolean bool = verify(params1,sign1,pk);
		System.out.println(bool);

//		final String sign = sign("123456789876543223456789876543234567898765432", "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMqnmT2/IbaX337ToGt+0y/hR816UEb9F3HUwCqSqesE5otgRmGS5ztQ+SSZSkDTEa/zd5+vPqvtSPwGoiiZ5t2yTPiLqW7JtxDsRJzUZZilkEHINETBgGLw/SOS6z/11RWkQFNfUMCiqoC8a7OVUqEiEMOtjRyPq6onml8j8BCnAgMBAAECgYEApx870p3ykYABgbfITZ3TT2L7McqytTg2w1rt9q3ojrYF4d7Na94X7uTB8Zqwj3EA3xdrCTcd+e6/B4f45n600ZrEggL85PgJ+padCifZMGRQVKyTWLXVujZEANj6h00DlBPA1aflX4lCuvr7jwTd+x/pPlkIOZEvccH3YdwrlKECQQDx3qy5EDDxUCTGzxnzt4E9/SfcwdXVaxME2/O9w4ZbJ04i7nH9JF5qqajMaohbSY7kQ1Dkbk9B1G1sUIgQGQEPAkEA1n5vaDx/QTr2fQ1M0XMs1fcAz5XqIyQBVyjCoy+WLQKsw880+55q9bAqstd3hgbCgRS5oGHGscVgGT/zYtxG6QJAf16T9qDgJTPfKhLFx+JK3SoDY+1vfgP08AokQTpF9pqsOxj2Tiho0CKoEX3IcMo7xVjtsF2mvzPuq6t8+30vYQJAczwADGccEuZjkHF5yLjw6I7ID75ByNlKIxJR5yvkqY/bU2NZ2qiUXCRl/CkIHKg7DPAefgypm84nP8l8r6saKQJAbcOdQzJ4DFfRAkPQ+pdPxDfxFLWrDVPdSG5yR1gmb1swNdQq88lvoSIS/qUpSUPZ0eb1g3n/xvW/fNWq7Fuajg==");
//		System.out.println(sign);

	}
}
